package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.squareup.picasso.Picasso;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.RealNameBean;
import com.zhongjian.technologycal.mall.net.ApiRetrofitClient;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.utils.ValidatorUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/25.
 * 申请实名认证页面实现
 */

public class RealNameActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.commit_realname_et_name)
    EditText commit_realname_et_name;
    @BindView(R.id.commit_et_phone)
    EditText commit_et_phone;
    @BindView(R.id.idcard_et)
    EditText idcard_et;
    @BindView(R.id.photo0)
    ImageView photo0;
    @BindView(R.id.photo1)
    ImageView photo1;
    @BindView(R.id.photo2)
    ImageView photo2;
    private int type = 0;
    @BindView(R.id.realname_tv_status)
    TextView realname_tv_status;
    @BindView(R.id.apply_tv_commit)
    TextView apply_tv_commit;
    private Dialog picChooseDialog = null;
    private String imgUrl0;
    private String imgUrl1;
    private String imgUrl2;
    private Dialog hintDialog = null;
    private ArrayList<String> selectedPhotos = new ArrayList<>();

    private static final int IMAGE_PICKER = 5;
    private static final int REQUEST_CODE_SELECT = 6;

    @Override
    protected void beforeInit() {
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("实名认证");
        initViewRequest();
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_apply_realname;
    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    /**
     * 实名认证提交
     */
    @OnClick(R.id.apply_tv_commit)
    public void onClickApplyCommit() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        } else if (TextUtils.isEmpty(commit_realname_et_name.getText().toString().trim())) {
            ToastUitl.showShort("真实姓名不能为空～");
            return;
        } else if (TextUtils.isEmpty(commit_et_phone.getText().toString().trim())) {
            ToastUitl.showShort("手机号不能为空～");
            return;
        } else if (TextUtils.isEmpty(idcard_et.getText().toString().trim())) {
            ToastUitl.showShort("身份证号不能为空～");
            return;
        } else if (!ValidatorUtils.isLegalId(idcard_et.getText().toString().trim())) {
            ToastUitl.showShort("身份证号不正确，请检查重新输入～");
            return;
        } else if (TextUtils.isEmpty(imgUrl0)) {
            ToastUitl.showShort("请先上传证件图片～");
            return;
        } else if (TextUtils.isEmpty(imgUrl1)) {
            ToastUitl.showShort("请先上传证件图片～");
            return;
        } else if (TextUtils.isEmpty(imgUrl2)) {
            ToastUitl.showShort("请先上传证件图片～");
            return;
        }

        Map<String, String> maps = new HashMap<String, String>();
        maps.put("truename", commit_realname_et_name.getText().toString().trim());
        maps.put("phone", commit_et_phone.getText().toString().trim());
        maps.put("idcardno", idcard_et.getText().toString().trim());
        maps.put("idcardphoto", imgUrl0);
        maps.put("idcardphoto2", imgUrl1);
        maps.put("idcardphoto3", imgUrl2);

        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));

        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestRealName(UserUtils.getUserToken(),
                        body, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(RealNameActivity.this);
                            }

                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onError(Throwable e) {
                                LoadingDialog.cancelDialogForLoading();
                                ToastUitl.showShort(e.getMessage());

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        ToastUitl.showShort("提交实名认证成功，请耐心等候后台审核～");
                                        finish();
                                    } else if (baseBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });


    }

    private void requestUploadToImage(String path) {
        File file = new File(path);
        final RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        ApiRetrofitClient.getInstance(getBaseContext()).postUrlRequestUploadPhoto(body,
                UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(RealNameActivity.this, "上传中...", true);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        Log.v("----", e.getMessage());
                    }


                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                ToastUitl.showShort("上传成功～");
//                                final RequestOptions options = new RequestOptions();
//                                String updateTime = String.valueOf(System.currentTimeMillis()); // 在需要重新获取更新的图片时调用
//                                options.centerCrop()
////                                        .transform(new GlideRoundTransform(mContext,5))
//                                        .skipMemoryCache(true)
//                                        .diskCacheStrategy(DiskCacheStrategy.NONE)//
//                                        .placeholder(R.mipmap.bg_white2x)
//                                        .error(R.mipmap.bg_white2x);
                                if (type == 0) {
                                    Picasso.get().load(BaseContacts.BASE_URL + baseBean.getData().toString()).into(photo0);
                                    imgUrl0 = baseBean.getData().toString();

                                } else if (type == 1) {
                                    Picasso.get().load(BaseContacts.BASE_URL + baseBean.getData().toString()).into(photo1);
                                    imgUrl1 = baseBean.getData().toString();

                                } else if (type == 2) {
                                    imgUrl2 = baseBean.getData().toString();
                                    Picasso.get().load(BaseContacts.BASE_URL + baseBean.getData().toString()).into(photo2);
                                }

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    @OnClick(R.id.photo0)
    public void onClickUpload0() {
        type = 0;
        picChooseDialog = new Dialog(this, R.style.pic_choose_dialog_progress);
        View view = LayoutInflater.from(getBaseContext()).inflate(
                R.layout.pic_choose_dialog, null);
        TextView choose_tv_photo1 = (TextView) view
                .findViewById(R.id.choose_tv_photo1);
        TextView choose_tv_photo2 = (TextView) view
                .findViewById(R.id.choose_tv_photo2);
        TextView choose_tv_cancel = (TextView) view
                .findViewById(R.id.choose_tv_cancel1);
        /**
         * 从相册选图
         */
        choose_tv_photo1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                picChooseDialog.dismiss();
            }
        });
        /**
         * 相机拍照
         */
        choose_tv_photo2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                picChooseDialog.dismiss();
            }
        });

        // 取消
        choose_tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                picChooseDialog.dismiss();
            }
        });

        Window window = picChooseDialog.getWindow();
        window.setContentView(view);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(android.view.WindowManager.LayoutParams.MATCH_PARENT,
                android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        window.setWindowAnimations(R.style.popupWindowAnimation);
        picChooseDialog.setCanceledOnTouchOutside(true);
        picChooseDialog.show();

    }

    @OnClick(R.id.photo1)
    public void onClickUpload1() {
        type = 1;
        picChooseDialog = new Dialog(this, R.style.pic_choose_dialog_progress);
        View view = LayoutInflater.from(getBaseContext()).inflate(
                R.layout.pic_choose_dialog, null);
        TextView choose_tv_photo1 = (TextView) view
                .findViewById(R.id.choose_tv_photo1);
        TextView choose_tv_photo2 = (TextView) view
                .findViewById(R.id.choose_tv_photo2);
        TextView choose_tv_cancel = (TextView) view
                .findViewById(R.id.choose_tv_cancel1);

        choose_tv_photo1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                picChooseDialog.dismiss();
            }
        });
        /**
         * 相机拍照
         */
        choose_tv_photo2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                picChooseDialog.dismiss();

            }
        });

        // 取消
        choose_tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                picChooseDialog.dismiss();
            }
        });

        Window window = picChooseDialog.getWindow();
        window.setContentView(view);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(android.view.WindowManager.LayoutParams.MATCH_PARENT,
                android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        window.setWindowAnimations(R.style.popupWindowAnimation);
        picChooseDialog.setCanceledOnTouchOutside(true);
        picChooseDialog.show();

    }

    @OnClick(R.id.photo2)
    public void onClickUpload2() {
        type = 2;
        picChooseDialog = new Dialog(this, R.style.pic_choose_dialog_progress);
        View view = LayoutInflater.from(getBaseContext()).inflate(
                R.layout.pic_choose_dialog, null);
        TextView choose_tv_photo1 = (TextView) view
                .findViewById(R.id.choose_tv_photo1);
        TextView choose_tv_photo2 = (TextView) view
                .findViewById(R.id.choose_tv_photo2);
        TextView choose_tv_cancel = (TextView) view
                .findViewById(R.id.choose_tv_cancel1);
        /**
         * 从相册选图上传
         */
        choose_tv_photo1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                picChooseDialog.dismiss();
            }
        });
        /**
         * 相机拍照上传图片
         */
        choose_tv_photo2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                picChooseDialog.dismiss();
            }
        });

        // 取消
        choose_tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                picChooseDialog.dismiss();
            }
        });

        Window window = picChooseDialog.getWindow();
        window.setContentView(view);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(android.view.WindowManager.LayoutParams.MATCH_PARENT,
                android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        window.setWindowAnimations(R.style.popupWindowAnimation);
        picChooseDialog.setCanceledOnTouchOutside(true);
        picChooseDialog.show();
    }

    /**
     * 初始化数据
     */
    private void initViewRequest() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).getUrlRequestByInfo(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(RealNameActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                        ToastUitl.showShort(e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            RealNameBean realNameBean = gson.fromJson(responseBody.string(), RealNameBean.class);
                            if (realNameBean.getError_code() == 0) {
                                if (realNameBean.getData().getIsAuth() == -1) {
                                    realname_tv_status.setVisibility(View.VISIBLE);
                                    realname_tv_status.setText("审核失败,请重新提交资料");
                                    commit_realname_et_name.setFocusable(true);
                                    commit_et_phone.setFocusable(true);
                                    idcard_et.setFocusable(true);
                                    photo0.setClickable(true);
                                    photo1.setClickable(true);
                                    photo2.setClickable(true);
                                } else if (realNameBean.getData().getIsAuth() == 1) {
                                    realname_tv_status.setVisibility(View.VISIBLE);
                                    realname_tv_status.setText("审核中...");
                                    apply_tv_commit.setVisibility(View.GONE);
                                    commit_realname_et_name.setText(realNameBean.getData().getTrueName());
                                    commit_et_phone.setText(realNameBean.getData().getPhone());
                                    idcard_et.setText("" + realNameBean.getData().getIDCardNo());
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto()).into(photo0);
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto2()).into(photo1);
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto3()).into(photo2);

                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto()).into(photo0);
                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto2()).into(photo1);
                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto3()).into(photo2);

                                    commit_realname_et_name.setFocusable(false);
                                    commit_et_phone.setFocusable(false);
                                    idcard_et.setFocusable(false);
                                    photo0.setClickable(false);
                                    photo1.setClickable(false);
                                    photo2.setClickable(false);

                                } else if (realNameBean.getData().getIsAuth() == 2) {
                                    realname_tv_status.setVisibility(View.VISIBLE);
                                    realname_tv_status.setText("实名认证已审核通过");
                                    apply_tv_commit.setVisibility(View.GONE);
                                    commit_realname_et_name.setText(realNameBean.getData().getTrueName());
                                    commit_et_phone.setText(realNameBean.getData().getPhone());
                                    idcard_et.setText("" + realNameBean.getData().getIDCardNo());
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto()).into(photo0);
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto2()).into(photo1);
//                                    Glide.with(getBaseContext()).load(BaseContacts.BASE_URL +
//                                            realNameBean.getData().getIDCardPhoto3()).into(photo2);

                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto()).into(photo0);
                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto2()).into(photo1);
                                    Picasso.get().load(BaseContacts.BASE_URL +
                                            realNameBean.getData().getIDCardPhoto3()).into(photo2);
                                    commit_realname_et_name.setFocusable(false);
                                    commit_et_phone.setFocusable(false);
                                    idcard_et.setFocusable(false);
                                    photo0.setClickable(false);
                                    photo1.setClickable(false);
                                    photo2.setClickable(false);

                                } else if (realNameBean.getData().getIsAuth() == 0) {
                                    realname_tv_status.setVisibility(View.GONE);
                                    realname_tv_status.setText("请提交实名认证");
                                    apply_tv_commit.setVisibility(View.VISIBLE);
                                    commit_realname_et_name.setFocusable(true);
                                    commit_et_phone.setFocusable(true);
                                    idcard_et.setFocusable(true);
                                    photo0.setClickable(true);
                                    photo1.setClickable(true);
                                    photo2.setClickable(true);
                                }

                            } else if (realNameBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);

                            } else {
                                ToastUitl.showShort(realNameBean.getError_message());
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String imgpath = images.get(0).path;
                requestUploadToImage(imgpath);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images1 = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String imgpath = images1.get(0).path;
                requestUploadToImage(imgpath);
            } else {
                ToastUitl.showShort("没有图片数据～");
            }
        }

    }
}
